package com.mocha.base.web;


import com.mocha.common.core.MochaException;
import com.mocha.common.core.MochaResponse;
import com.mocha.common.core.ResponseCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author: songkui
 * @version: 1.0
 * @date: 2019/5/25 12:40
 * @apiNote: 统一返回异常数据格式
 */
@Slf4j
@ControllerAdvice
@ResponseBody
public class MochaGlobalExceptionHandler {

    private static final String logExceptionFormat = "Capture Exception By GlobalExceptionHandler: Code: %s ,Detail: %s";

    //运行时异常
    @ExceptionHandler(MochaException.class)
    public MochaResponse runtimeExceptionHandler(MochaException ex) {
        log.error("MochaException: {}", ex.getMessage());
        return MochaResponse.responseCode(ex.getState());
    }

    /**
     * 校验错误拦截处理
     *
     * @param exception 错误信息集合
     * @return 错误信息
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public MochaResponse validationBodyException(MethodArgumentNotValidException exception) {
        BindingResult result = exception.getBindingResult();
        if (result.hasErrors()) {
            List<ObjectError> errors = result.getAllErrors();
            ObjectError e = errors.get(0);
            FieldError fieldError = (FieldError) e;
            log.error("MethodArgumentNotValidException:  object{},field{},errorMessage{}}", fieldError.getObjectName(), fieldError.getField(), fieldError.getDefaultMessage());
            return MochaResponse.response(fieldError.getDefaultMessage(), ResponseCode.ParamInvalid);
        }
        return MochaResponse.responseCode(ResponseCode.ParamInvalid);
    }

    @ExceptionHandler({Exception.class})
    public MochaResponse exception(Exception ex) {
        log.error("Exception: ", ex);
        return MochaResponse.responseCode(ResponseCode.SysException);
    }



}
